/*
 * @Author: June
 * @Date: 2022-11-14 14:40:09
 * @LastEditors: 无处安放的六月
 * @LastEditTime: 2023-12-07 10:05:00
 * @Description:
 *
 */
import { getIsAdmin, getToken, getCompInfo } from '@/utils/auth' // get token from cookie
import { getFieldsByRoute } from '@/utils/function'
import getPageTitle from '@/utils/get-page-title'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import router from './router'
import store from '@/store'
import { Message } from 'element-ui'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  // console.log(getCompInfo())
  const { compShortName, compName } = getCompInfo()
  document.title = `${to.meta.title} ${compShortName || compName ? `- ${compShortName || compName}` : ''}` //  getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      if (!getIsAdmin() && to.path === '/companyInformation') {
        next({ path: '/404' })
        NProgress.done()
      } else {
        const hasMenuList = await store.getters.routeList
        if (Array.isArray(hasMenuList)) {
          //  进入路由之前先获取当前页面字段
          getFieldsByRoute(to.fullPath).then(res => {
            next()
            NProgress.done()
          })
        } else {
          try {
            await store.dispatch('canStantRouter/GenerateRoutes')
            next({ ...to, replace: true }) // 重载 beforeEach 操作
          } catch (error) {
            await store.dispatch('user/resetToken')
            Message.error(error || 'Has Error')
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          }
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  // finish progress bar
  NProgress.done()
})
